package com.jawmask.android.stuartproair.ui;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.jawmask.android.stuartproair.R;

public abstract class BaseListActivity extends BaseActivity implements OnItemClickListener {

	private ListView listView;
	private ListAdapter listAdapter;

	protected void setListAdapter(final ListAdapter listAdapter) {
		this.listAdapter = listAdapter;
		listView = (ListView) findViewById(android.R.id.list);
		listView.setAdapter(this.listAdapter);
		listView.setOnItemClickListener(this);
	}

	protected ListAdapter getListAdapter() {
		return this.listAdapter;
	}

	@Override
	public void onItemClick(AdapterView<?> vistView, View view, int position, long id) {
		onListItemClick(listView, view, position, id);
	}

	abstract protected void onListItemClick(ListView vistView, View view, int position, long id);

	protected final class ListItemAdapter extends ArrayAdapter<String> {

		private String[] text2Array;

		public ListItemAdapter(final String[] objects) {
			super(BaseListActivity.this, -1, objects);
		}

		public ListItemAdapter(final String[] objects, String[] text2Array) {
			super(BaseListActivity.this, -1, objects);
			this.text2Array = text2Array;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View contentView = convertView;
			if (contentView == null) {
				LayoutInflater vi = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				contentView = vi.inflate(R.layout.list_item_layout, parent, false);

				ViewHolder viewHolder = new ViewHolder();
				viewHolder.itemValue = (TextView) contentView.findViewById(android.R.id.text1);
				viewHolder.text2Value = (TextView) contentView.findViewById(android.R.id.text2);

				contentView.setTag(viewHolder);
			}

			ViewHolder viewHolder = (ViewHolder) contentView.getTag();
			String item = getItem(position);
			if (text2Array != null) {
				String itemText2 = text2Array[position];
				viewHolder.text2Value.setVisibility(View.VISIBLE);
				viewHolder.text2Value.setText(itemText2);
			} else {
				viewHolder.text2Value.setVisibility(View.GONE);
			}

			viewHolder.itemValue.setText(item);

			return contentView;
		}
	}

	private final static class ViewHolder {
		TextView itemValue;
		TextView text2Value;
	}
}